package blue.http.internal.core.net.response;

import blue.http.core.message.HttpResponse;
import blue.http.core.options.HttpOptions;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jin Zheng
 * @since 1.0 2020-01-14
 */
public class ResponseHandlerFactory {
	private static Logger logger = LoggerFactory.getLogger(ResponseHandlerFactory.class);

	private List<ResponseHandler> handlerList = new ArrayList<>();

	public ResponseHandlerFactory(HttpOptions options) {
		handlerList.add(new NullResponseHandler());
		handlerList.add(new ViewResponseHandler(options.getViewRoot()));
		handlerList.add(new DownloadResponseHandler());
		handlerList.add(new JsonResponseHandler());
	}

	public void handle(Channel ch, HttpRequest request, HttpResponse response) {
		if (response == null) {
			logger.warn("Response is null");
			return;
		}

		Object result = response.getResult();
		for (ResponseHandler handler : handlerList) {
			if (handler.accepted(result)) {
				logger.debug("Response result with: {}", handler.getClass().getName());
				handler.handle(ch, request, response);
				break;
			}
		}
	}

}
